/** @jsxImportSource @emotion/react */
import {jsx, css} from "@emotion/react";
import * as React from "react";
//import { usePaginateQueryTask } from "./db";
import {
    List,
    ListItem,
    Text, Stack, StackTitle, StackItem,
    useTheme,
    IconChevronRight,
    VerticalMenu, DdMenuItem, Button, useToast, ListFlexRow, Itext
} from "customize-easy-ui-component";
//import { SearchBox } from "../SearchBox";
//import debug from "debug";
//import algoliasearch from "algoliasearch";
//import config from "./firebase-config";
//import { useSession } from "../auth";
//import find from "lodash.find";
//import { useDeleteRequestFollow, usePaginateQueryUser,  } from "./db";
//import { StackItem } from "react-gesture-stack";
//import { useLocation } from "wouter";
//import { BoundReports } from "./report/BoundReports";
import {usePaginationFragment, useRefetchableFragment, useRelayEnvironment} from "react-relay/hooks";
import {UserTaskList$key} from "./__generated__/UserTaskList.graphql";
import {useContext, } from "react";
import RoutingContext from "../routing/RoutingContext";
// import {Stack, StackTitle, StackItem,} from "../../UiDebugSave/sample/Stack";
import {RecordSource} from "relay-runtime";
import {useZeebeRead} from "./report/localUpdateRelay";


const graphql = require("babel-plugin-relay/macro");


interface UserTaskListProps {
    isps: UserTaskList$key;
}

export const UserTaskList: React.FunctionComponent<UserTaskListProps> = props => {
  const theme = useTheme();
  //const toast = useToast();
 // const {user,} = useSession();
  //const [, setLocation] = useLocation();
  //graphQl的查询usexxx钩子函数，无法主动从后端读取最新数据。
  //const { loading, userList:followings } = useFollowerIngs(false);
  let filtercomp={filter: { id:1 },
    offset:0,
    limit:5,
    orderBy: "id",
    asc: false
  };
    const { data, refetch , loadNext,hasNext,isLoadingNext} = usePaginationFragment(
        graphql`
            fragment UserTaskList on Query
            @refetchable(queryName: "getTodosQuery") {
                getTodos(where: $iwhere,after:$after,first:$first,orderBy:$orderBy,asc:$asc)
                @connection(key: "Query__getTodos") {
                    __id
                    edges {
                        node {
                            id,processName,name,assignee,candidateGroups,creationTime,
                            uri,ent,expirationDate,topic,prId,say,tdId,pren
                        }
                    }
                }
            }
        `,
        props.isps,
    );
    //const cID=data?.__id;=='client:root'对照data?.getTodos?.__id;=='client:root:__Query__getTodos_connection(asc:true)'
    const { getTodos:list, }=data;
    const connectionID= data?.getTodos?.__id;
    //下面点击列表允许能够直接删除列表被点击那一条对应的isps;
    let jobs = list?.edges?.map(edge => {
        const {creationTime,expirationDate,...other} = { ... edge?.node};
        return { ...other,
            creationTime: creationTime?.substring(5,16),
            expirationDate: expirationDate?.substring(5,16)
            };
        } );
  //搜索user的输入:
  const [query, setQuery] = React.useState("");
    const toast = useToast();

  const [, setFilter] = React.useState({where:
        {cod:query },
     });

  const noUsers = !query && (jobs?.length === 0);
  //界面轮播 setIndex切换显示界面；   //index不是组件外部那一个同名index；
  const [index, setIndex] = React.useState(0);
    const {history } = useContext(RoutingContext);

  React.useEffect(() => {
    //console.log("伪善setQueryResul02=" ,query,usersFind);
    let filtercomp={where:
        {cod:query },
      offset:0,
      first:5,
      orderBy: "useDt",
      asc: false
    };
    setFilter(filtercomp);
  }, [query]);
  //这两个useEffect的前后顺序不能颠倒，顺序非常重要，后面的依赖于前面的useEffect更新结果。
  //操作UI副作用；要进一步做修正性处理。
  //   React.useEffect(() => {
  //       //不知道是否刚刚查询的？   待办列表进入会查询第二次。
  //       refetch({}, { fetchPolicy: "network-only"});
  //   }, [refetch]);
    //是否需要再次依照后端的查询来更新页面显示。可惜路由切换再回来的都是frserver=true;
    //路由切换再回来的只能使用Relay Store来删除已经被点击的用户任务条，不能上本机修改队列方式。
    const {call:deleteUserTask}= useZeebeRead();
  return (
    <Stack   navStyle={css({ position: 'sticky',  top: 0,})}
             style={{
              //   overflow: 'unset'
             }}
      index={index}
      navHeight={40}
      onIndexChange={i => setIndex(i)}
      items={[
        {
          title: (
              <StackTitle
                  contentAfter={
                      <VerticalMenu>
                          <DdMenuItem label="刷新吧" onClick={(e) => {
                              refetch({}, { fetchPolicy: "network-only"});
                              // setFrserver(true);
                          }} />
                      </VerticalMenu>
                  }
                  title={"我的流程待处理事务"}
              />
          ),
          content: (
              <StackItem className="ItemConte"
                         css={{
                          //   marginBottom: `${barHeight}`,
                         }}
                         style={{ position: undefined, boxShadow:undefined }}
              >
              <div
                css={{
                  overflowY: "auto",
                  //overflowY: "scroll", 滚动触发，小屏幕很明显的条，滚动条会随浏览器屏幕设备模式变化样式。
                  height: "100%",
                  minWidth: '19rem',
                  minHeight: '14rem',
                    display: 'flex',
                    justifyContent: 'center',
                    flexDirection: 'column',
                }}
              >
                { noUsers && (
                    <>
                        <Text  muted
                               css={{
                                   fontSize: theme.fontSizes[0],
                                   display: "block",
                                   margin: theme.spaces.lg
                               }}
                        >待办队列为空或者都刚刚看
                        </Text>
                    </>
                )}
                { !noUsers && (
                <List>
                 {jobs?.map((item,i) => {
                   //这样的<RouterLink <ListItem onPress={() =>showRelation ;可能会ListItem报错unmounted:仅当嵌入为报告/动态模板之内；
                   return (
                       item &&
                       <ListFlexRow  key={item?.id}
                             onPress={async (e) => {
                                 e?.stopPropagation();
                                 e?.preventDefault();
                                 //短期保存，刷新UserTask时清空，明显脱离主体页面的可清空: 【问题】适用?可能已经脱离了已经点击的审批报告待审批实现的页面呢？#避免尝试歧义。
                                 sessionStorage['审批单'] =JSON.stringify({'entId':`${item?.ent}`,'utId':`${item?.id}`,
                                     'fNode':`${item?.name}`,tdId: item?.tdId,process: item?.processName,say: item?.say,pren: item?.pren});
                                 //多个系统之间的关联？ URI尽量不要前缀的IP 域名端口号，感觉更恰当。
                                 deleteUserTask(connectionID!, item?.id!);     //点就从界面移除:不涉及后端服务端：需要刷新才能重新看见！
                                 // jobs!.splice(i,1);
                                 history.push(`${item?.uri}`);
                             } }
                             contentAfter={
                                 <IconChevronRight
                                     color={theme.colors.text.muted}
                                     aria-hidden
                                 />
                             }
                             /*消除上下两级组件AloneContainer ListFlexRow都会预留padding,避免小屏幕太多空隙了。*/
                             css={[ {
                                     padding: "0.15rem 0",
                                     [theme.mediaQueries.md]: {
                                         padding: `0.15rem 0.2rem`,
                                     },
                                 }, ]}
                       >
                           <Text>{item?.topic}</Text>
                           <Itext>{ item?.name || '#'}</Itext>
                           <Itext>{`${item?.processName}`}</Itext>
                           <Itext>从{ item?.creationTime }</Itext>
                           <Itext>{ item?.expirationDate }截止</Itext>
                           <Text>{ item?.say }</Text>
                       </ListFlexRow>
                    );
                  })}
                </List>
                )}
                  <div
                      css={{
                          textAlign: "center",
                          marginBottom: theme.spaces.md,
                          marginTop: theme.spaces.md
                      }}
                  >
                          <div css={{
                              display: 'flex',
                              justifyContent: 'space-evenly',
                          }}>
                              <Button disabled={isLoadingNext}
                                      onPress={async (e) => {
                                          e?.stopPropagation();
                                          await loadNext(10,{
                                              onComplete: (error) => {
                                                  // setFrserver(true);
                                                  if (error) {
                                                      toast({
                                                          title: "返回了",
                                                          subtitle: "" + error,
                                                          intent: "error"
                                                      });
                                                  }
                                              },
                                              });
                                          }
                                      }
                              >
                                  按，拉扯获取更多......
                              </Button>
                              <Button intent="primary" disabled={isLoadingNext}
                                      onPress={async (e) => {
                                          refetch({}, { fetchPolicy: "network-only"});
                                      } }
                              >
                              刷新
                              </Button>
                          </div>
                  </div>
              </div>
            </StackItem>
          )
        }
      ]}
    />
  );
};



//报错Cannot read property 'map' of null标记出错代码行，竟可能会差错！实际错误点实在下方，报错指示却在上方的代码行，两处都有.map的代码。
//<Stack 组件，实际上是内部状态控制界面的呈现，实际上DOM数据内容并没有同步地变更，只是页面切换着看；适用数据库组织的；PK的，导航堆叠场景实际是源代码组织的。
//幸运的事！！<StackItem>底下内嵌的组件可以做到每一个都是独立自主的。这里<FollowingRecipes key={}/>对每一个按钮进入和后退的，虽然组件同一个，但内部状态数据可各自独立的。
//overflowY:"scroll"若遇到 css={{height: "100%", 和 minHeight: '300px' 不能同时添加的。overflowY:和"100%"一起使用，且要在内层DIV上用。组件中间层可能屏蔽掉。
//多层DIV的height: "100%", 需要在中间层次添加100%传递父辈限制大小，配合内部层的overflowY: "scroll",才能滚动。
//<Stack多层的下沉层叠＋<ListItem，配合<RouterLink，可以触发点击链接同时还能够下沉页面触发；左右两个页面都能刷新，可是小屏幕只能对照右半部分的核心界面。不触发下沉和要触发条目可同时用。
//点击一次触发多重：<RouterLink to={`/inspect/${item.id}`} >    /  <ListItem  onPress={() =>      /   <Button  onPress={e => { ；；
